home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1904 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  100 lines

  1. Path: guillotine.mtl.dmr.ca!news
  2. From: Bernard Drolet <Bernard.Drolet@dmr.ca>
  3. Newsgroups: comp.lang.c++
  4. Subject: Typecasting
  5. Date: Fri, 12 Jan 1996 23:48:00 -0800
  6. Organization: Groupe DMR
  7. Message-ID: <30F763B0.319@dmr.ca>
  8. NNTP-Posting-Host: slip29.mtl.dmr.ca
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.0b3 (Win16; I)
  13.  
  14. I'm writing a program using the Doc-View method.
  15.  
  16. Presently, the main classes are (simplified)
  17.  
  18. class Base
  19. {
  20.    int GetType() = 0;
  21.    // some other methods and variables
  22. };
  23.  
  24. class A : public Base
  25. {
  26.    int GetType() { return TypeA; }
  27.    // methods and variables
  28. };
  29.  
  30. class B : public Base
  31. {
  32.    int GetType() { return TypeB; }
  33.    // methods and variables
  34. };
  35.  
  36. class Doc
  37. {
  38.    List<Base> ListOfBaseObjects;
  39.    Doc();
  40. };
  41.  
  42. class View
  43. {
  44.    Doc CurrentDocument;
  45.    void Paint();    
  46.    void PaintAObject();
  47.    void PaintBObject();
  48. };
  49.  
  50. void Doc::Doc()
  51. {
  52.    A* a = new A();
  53.    B* b = new B();
  54.  
  55.    ListOfBaseObjects.Add(a);
  56.    ListOfBaseObjects.Add(b);
  57. }
  58.    
  59. void View::Paint()
  60. {
  61.    Iterator<CurrentDocument.ListOfBaseObjects> ObjectsIterator;
  62.  
  63.    while ( ObjectsIterator )
  64.    {
  65.       switch ( ObjectsIterator.Current()->GetType() )
  66.       {
  67.          case TypeA:
  68.             PaintAObject();
  69.             break;
  70.          case TypeB:
  71.             PaintBObject();
  72.             break;
  73.       }
  74.       ObjectsIterator++;
  75.    }
  76. }
  77.  
  78.  
  79. What I would like better is to remove the switch statement in the paint() function and 
  80. find a way to define functions looking like Paint(A& a), Paint(B& b) and to call them 
  81. directly, but is there a way to discover what type an object that was inserted in the list 
  82. is?
  83.  
  84. I would like to replace the switch in the paint() with a statement like
  85.    while ( ObjectsIterator )
  86.    {
  87.       Paint(ObjectsIterator.Current())
  88.       ...
  89.  
  90. So can I typecast the abstract Base object contained in the list to its actual type ?
  91.  
  92.  
  93.  
  94. ==========================================================
  95. Bernard Drolet                       Bernard.Drolet@dmr.ca
  96. Groupe DMR
  97. 1200 McGill College
  98. Montreal, Quebec, Canada
  99. ==========================================================
  100.